package StudyCode.summary.Basic.myarray;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class BinarySearch {

	public static void main(String[] args) {
		int[] v = {1, 5, 9, 12, 16, 27, 39, 63, 84, 94, 102, 89};
		System.out.println("二分法查找元素39,索引是:" + dichotomySearch(v, 39));
	}

	public static int dichotomy(int[] array, int left, int right, int key) {
		if (left > right)
			return -1;

		int m = (left + right) / 2;

		if (array[m] == key) {
			return m;
		} else {
			if (array[m] < key) {
				return dichotomy(array, m + 1, right, key);
			} else {
				return dichotomy(array, left, m - 1, key);
			}
		}
	}

	public static int dichotomySearch(int[] array, int key) {
		return dichotomy(array, 0, array.length - 1, key);
	}
}
